package com.example.emergencyattempt01.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import com.example.emergencyattempt01.R;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import android.os.Handler;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import org.json.JSONException;
import org.json.JSONObject;

public class IngTab_ListViewAdapter extends BaseAdapter {
    List<Map<String,Object>> itemList;
    Context context;
    ViewHolder viewHolder;


    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int postion=(int)msg.obj;
            switch (msg.what)
            {
                case SEND_SUCCESS:
                    Toast.makeText(context,"已成功发送，正在等待管理员审核",Toast.LENGTH_SHORT).show();
                    itemList.remove(postion);
                    notifyDataSetChanged();
                    break;
                case SEND_FAIL:
                    Toast.makeText(context,"发送失败，请检查网络",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    final int SEND_SUCCESS=0x001;
    final int SEND_FAIL=0x002;


    class ViewHolder{
        TextView bidField;
        TextView lidField;
        TextView uidField;
        TextView userNameField;
        TextView identityField;
        TextView ownBooksField;
        TextView bookNameField;
        TextView ISBNField;
        TextView borrowTimeField;

        TextView lastTimeField;
        ImageView timeOutMarker;

        Button returnBook;
        Button continueBorrow;
    }

    public IngTab_ListViewAdapter(List<Map<String, Object>> itemList, Context context) {
        this.itemList = itemList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return (long)itemList.get(position).get("bid");
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        if (convertView==null)
        {
            convertView=inflater.inflate(R.layout.ing_tab_list_item,null);
            viewHolder=new ViewHolder();
            viewHolder.bidField=convertView.findViewById(R.id.ing_borrow_bid);
            viewHolder.uidField=convertView.findViewById(R.id.ing_borrow_uid);
            viewHolder.lidField=convertView.findViewById(R.id.ing_borrow_lid);
            viewHolder.bookNameField=convertView.findViewById(R.id.ing_borrow_bookName);
            viewHolder.borrowTimeField=convertView.findViewById(R.id.ing_borrow_borrowTime);
            viewHolder.userNameField=convertView.findViewById(R.id.ing_borrow_userName);
            viewHolder.identityField=convertView.findViewById(R.id.ing_borrow_identity);
            viewHolder.ownBooksField=convertView.findViewById(R.id.ing_borrow_ownBooks);
            viewHolder.ISBNField=convertView.findViewById(R.id.ing_borrow_ISBN);
            viewHolder.lastTimeField=convertView.findViewById(R.id.ing_lastTime);
            viewHolder.timeOutMarker=convertView.findViewById(R.id.ing_time_out);

            viewHolder.continueBorrow=convertView.findViewById(R.id.ing_continue);
            viewHolder.returnBook=convertView.findViewById(R.id.ing_return_book);

            convertView.setTag(viewHolder);
        }
        else
        {
            viewHolder=(ViewHolder) convertView.getTag();
        }
        // 获取各值
        final long bid;
        long lid;
        long uid;
        String userName;
        String identity;
        String bookName;
        int ownBooks;
        String ISBN;
        long borrowTime;
        long lastTime;
        String returnIsConfirmed;

        uid=(long)itemList.get(position).get("uid");
        bid=(long)itemList.get(position).get("bid");
        lid=(long)itemList.get(position).get("lid");
        borrowTime=(long)itemList.get(position).get("borrowTime");
        lastTime=(long)itemList.get(position).get("lastTime");

        userName=(String)itemList.get(position).get("userName");
        identity=(String)itemList.get(position).get("identity");
        bookName=(String)itemList.get(position).get("bookName");
        ownBooks=(int)itemList.get(position).get("ownBooks");
        ISBN=(String)itemList.get(position).get("ISBN");
        returnIsConfirmed=(String)itemList.get(position).get("returnIsConfirmed");


        // 对单纯的文字部分设值
        viewHolder.uidField.setText("uid:"+uid);
        viewHolder.bidField.setText("借阅号:"+bid);
        viewHolder.lidField.setText("馆藏号:"+lid);
        viewHolder.userNameField.setText(userName);
        viewHolder.identityField.setText(identity);
        viewHolder.bookNameField.setText(bookName);
        if(ownBooks<=5)
            viewHolder.ownBooksField.setText(ownBooks+"本");
        else
            viewHolder.ownBooksField.setText("5本");
        viewHolder.ISBNField.setText(ISBN);

        // 对时间进行一个处理
        String borrowTimeDisplay=millisToString(borrowTime);
        viewHolder.borrowTimeField.setText(borrowTimeDisplay);

        // 剩余时间这件事。。。
        if(!returnIsConfirmed.equals("已同意"))
        {
            if(lastTime>0)
            {
                viewHolder.timeOutMarker.setVisibility(View.INVISIBLE);
                viewHolder.lastTimeField.setVisibility(View.VISIBLE);
                long sumSeconds = lastTime / 1000;
                long remainSeconds = sumSeconds % 60;
                long remainMinus = (long) Math.ceil((double) (sumSeconds / 60)) % 60;
                long remainHour = (long) Math.ceil((double) (sumSeconds / 3600)) % 24;
                long remainDay = (long) Math.ceil((double) (sumSeconds / 86400));
                String lastTimeString=remainDay + "天" + unifyForLast(remainHour) + "时" + unifyForLast(remainMinus) + "分" + unifyForLast(remainSeconds) + "秒";
                viewHolder.lastTimeField.setText((lastTimeString));
            }
            else
            {
                viewHolder.lastTimeField.setVisibility(View.INVISIBLE);
                viewHolder.timeOutMarker.setVisibility(View.VISIBLE);
            }
        }
        else
        {
            viewHolder.timeOutMarker.setVisibility(View.INVISIBLE);
            viewHolder.lastTimeField.setVisibility(View.VISIBLE);
            viewHolder.lastTimeField.setText("已归还");
            viewHolder.lastTimeField.setBackgroundResource(R.drawable.bg_frame_circle_time_out_display);
            viewHolder.lastTimeField.setTextColor(R.color.colorForName);
        }

        // 设置还书监听
        viewHolder.returnBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setMessage("确定要还书吗？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread()
                        {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject=new JSONObject();
                                    jsonObject.put("bid",bid);
                                    String toServer=String.valueOf(jsonObject);

                                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/return_book_request");
                                    int code=serverMessage.getRespondCode();
                                    if(code==200)
                                    {
                                        Message message=new Message();
                                        message.obj=position;
                                        message.what=SEND_SUCCESS;
                                        handler.sendMessage(message);
                                    }
                                    else {
                                        Message message=new Message();
                                        message.obj=position;
                                        message.what=SEND_FAIL;
                                        handler.sendMessage(message);
                                    }

                                }catch (JSONException e){e.printStackTrace();}
                                catch (IOException e){e.printStackTrace();
                                    Message message=new Message();
                                    message.obj=position;
                                    message.what=SEND_FAIL;
                                    handler.sendMessage(message);}
                            }
                        }.start();
                    }
                });
                builder.create().show();
            }
        });
        // 设置续借监听
        viewHolder.continueBorrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setMessage("确定要续借吗？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread()
                        {
                            @Override
                            public void run() {
                                try {
                                    JSONObject jsonObject=new JSONObject();
                                    jsonObject.put("bid",bid);
                                    String toServer=String.valueOf(jsonObject);

                                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/continue_request");
                                    int code=serverMessage.getRespondCode();
                                    if(code==200)
                                    {
                                        Message message=new Message();
                                        message.obj=position;
                                        message.what=SEND_SUCCESS;
                                        handler.sendMessage(message);
                                    }
                                    else {
                                        Message message=new Message();
                                        message.obj=position;
                                        message.what=SEND_FAIL;
                                        handler.sendMessage(message);
                                    }
                                }catch (JSONException e){e.printStackTrace();}
                                catch (IOException e){e.printStackTrace();
                                    Message message=new Message();
                                    message.obj=position;
                                    message.what=SEND_FAIL;
                                    handler.sendMessage(message);}
                            }
                        }.start();
                    }
                });
                builder.create().show();
            }
        });

        return convertView;
    }

    private String millisToString(long timeInMillis) {
        //新建一个calendar对象帮助转化出年月日时分秒
        Calendar calendar=Calendar.getInstance();
        calendar.setTimeInMillis(timeInMillis);
        /**
         * calendar中月份是从0起的
         */
        String year=unify( calendar.get(Calendar.YEAR));
        String month=unify( calendar.get(Calendar.MONTH)+1);
        String day=unify( calendar.get(Calendar.DATE));
        String hour=unify( calendar.get(Calendar.HOUR_OF_DAY));
        String minute=unify( calendar.get(Calendar.MINUTE));
        String second=unify( calendar.get(Calendar.SECOND));

        String target=year+"/"+month+"/"+day+"  "+hour+":"+minute+":"+second;
        return  target;
    }
    private String unify(int num)
    {
        String target=null;
        if(num<10)
        {
            target="0"+num;
        }
        else
            target=""+num;
        return target;
    }
    private String unifyForLast(long num)
    {
        String target=null;
        if(num<10)
        {
            target="0"+num;
        }
        else
            target=""+num;
        return target;
    }
}
